#!/usr/bin/env python3

from menu import Menu
from random import randint
from student import Student
import pickle

class StudentManage(Menu):
    """
    类的初始化
    """
    def __init__(self, **kargs):
        self.data = {}
        if "title" not in kargs:
            kargs["title"] = "========> 学生成绩管理系统 <========"
        super().__init__(**kargs)
        self.add("添加", self.addStu)
        self.add("修改", self.edit)
        self.add("查询", self.find)
        self.add("删除", self.delete)
        self.add("遍历", self.travel)
        self.add("存储", self.save)
        self.add("加载", self.load)

    """
    添加
    """
    def addStu(self, index):
        name = False
        while not name:
            name = input("\t请输入学生姓名: ")

        stu = Student(name)
        stu.age = randint(10, 30)
        stu.sex = ["男","女"][randint(0, 1)]
        stu.en = randint(50, 100)
        stu.cn = randint(0, 100)

        self.data[stu.id] = stu

    """
    修改
    """
    def edit(self, index):
        pass

    """
    删除
    """
    def delete(self, index):
        pass

    """
    遍历
    """
    def travel(self, index):
        for k, v in self.data.items():
            print("\t++++>" + v)

        print()

    """
    查询
    """
    def find(self, index):
        pass

    """
    存储和加载文件路径
    """
    @staticmethod
    def __getfile(mes, mode='rb'):
        filepath = input("\t%s(./db): " % mes)
        if not filepath:
            filepath = "./db"
        return open(filepath, mode)

    """
    加载
    """
    def load(self, index):
        data = pickle.load(self.__getfile("加载文件"))
        if (type(data) != dict
                or {'type', 'data', 'lastID'} - set(data)
                or 'type' not in data
                or 'data' not in data
                or 'lastID' not in data
                or data['type'] != 'kyo'):
            print("\t加载失败!")
        else:
            self.data = data['data']
            Student.setLastID(data['lastID'])
            print("\t加载成功!")

    """
    存储
    """
    def save(self, index):
        savedata = {}
        savedata['type'] = 'kyo'
        savedata['data'] = self.data
        savedata['lastID'] = Student.getLastID()
        pickle.dump(savedata, self.__getfile("存储到","wb"))
        print("\t存储成功!")

if __name__ == "__main__":
    StudentManage().run()
